<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item" label="气瓶编号:">
        <el-input v-model.trim="query.bottleCode" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="入库时间:" :table-form-merge="2" class="merge-item">
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="配送员名称:">
        <el-select v-model="query.ownerId" placeholder="请选择" clearable>
          <el-option
            v-for="(item,index) in ownersList"
            :key="index"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库仓库:">
        <el-select
          v-model="query.storeId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in rightStoreMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[70305,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <putStorageDetail ref="putStorageDetail" :stock-in-type-map="stockInTypeMap" :gd-status-map="gdStatusMap" />
    <div class="footText">查询条件下合计瓶数:{{ footerNum }}</div>
  </div>
</template>

<script>
  import {
    csDeliverUserList,
    invenstockInBillList,
    invenstockInBillScanCount,
    queryMap,
    stockTransWin
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import putStorageDetail from '../components/putStorageDetail.vue'
  export default {
    name: 'cylindersBack',
    components: {
      putStorageDetail
    },
    props: {
      storageStoreMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        rightStoreMap: [],
        truckMap: [],
        actionColWidth: 80,
        date: [],
        txt: '',
        footerNum: 0,
        query: {
          bottleCode: '',
          ownerId: '',
          storeId: ''
        },
        stockInTypeMap: [],
        stockOutTypeMap: [],
        gdStatusMap: [],
        tableData: {
          total: 0,
          data: []
        },
        ownersList: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'stockInCode',
            minWidth: 220,
            label: '入库单号',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.stockInCode}</el-link>
          },
          {
            prop: 'stockInType',
            label: '入库类型',
            minWidth: 120,
            render: (h, { row }) => <span>{ row.stockInType && formatColumnMap(this.stockInTypeMap, 'value', row.stockInType, 'desc') }</span>
          },
          {
            prop: 'storeName',
            label: '入库仓库',
            minWidth: 300,
            showOverflowTooltip: true
          },
          {
            prop: 'ownerName',
            label: '配送员',
            minWidth: 100
          },
          {
            prop: 'createUser',
            label: '入库人',
            minWidth: 100
          },
          {
            prop: 'enterDt',
            label: '入库时间',
            minWidth: 160,
            render: (h, { row }) => <span>{ row.enterDt && parseTime(row.enterDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'scanCount',
            label: '入库数量',
            minWidth: 100
          },
          {
            prop: 'bottleCodeStr',
            label: '气瓶编码',
            showOverflowTooltip: true,
            minWidth: 220
          }
        ]
      }
    },
    watch: {
      'storageStoreMap': {
        handler(newVal, oldVal) {
          if (newVal.length) {
            this.rightStoreMap = this.storageStoreMap
          }
        },
        deep: true,
        immediate: true
      }
    },
    async created() {
      await Promise.all([this.getTimeFn(), this.queryOptionsMap(), this.getOwnersList()])
    },
    methods: {
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.date[0] = parseTime(start, '{y}-{m}-{d}') + ' 00:00:00'
        this.date[1] = parseTime(end, '{y}-{m}-{d}') + ' 23:59:59'
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        if (this.date && this.date.length > 1) {
          query[`createTime`] = parseTime(this.date[0], '{y}-{m}-{d} {h}:{i}:{s}')
          query[`createTimeEnd`] = parseTime(this.date[1], '{y}-{m}-{d} {h}:{i}:{s}')
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          params: {
            ...this._getQuery(this.query),
            stockInType: 5
          },
          currentPage,
          pageSize
        }
        const res = await invenstockInBillList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        const res1 = await invenstockInBillScanCount(query)
        this.footerNum = res1.data || 0
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res, res3, res4] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'StockInType' }),
          stockTransWin(),
          mergeAsyncFunc(queryMap, { enumName: 'StockOutType' })
        ])
        this.stockInTypeMap = res.data // 入库类型
        this.stockOutTypeMap = res4.data // 出库类型
        this.gdStatusMap = JSON.parse(res3.data.gdStatusMap) // 商品状态枚举
      },

      // 入库单号
      async openDetail(row) {
        await this.$refs.putStorageDetail.open(row)
      },

      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 更新数据
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.$refs.form.resetFields()
      },
      // 查询处理人列表
      async getOwnersList() {
        this.ownersList = []
        const res = await csDeliverUserList({
          deliveryOrgId: this.userInfo.orgId,
          deliveryOrgSNNo: this.userInfo.orgSNNo
        })
        console.log(res.data)
        this.ownersList = res.data
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}

.footText {
  position: absolute;
  right: 10px;
  bottom: 5px;
  color: #F56C6C;
}
</style>
